<template>
	<view>
		
		<view>
			<!-- 查询工具/类型/时间 -->
			<view class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-padding-x">

				<view class="gui-margin-x">
					<gui-select-menu :items="query.typelist" @select="select_type" ref="selectMenu1"></gui-select-menu>
				</view>

				<view style="margin: 15rpx 20rpx; margin-right: 55rpx;">
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx;">开始日期:</text>
						<uni-datetime-picker start="2025-05-01" ref="ref_datePicker1" type="date" :clear-icon="false"
							v-model="query.start_date" @change="changeDate1" />
					</view>
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx">结束日期:</text>
						<uni-datetime-picker ref="ref_datePicker2" type="date" :clear-icon="false"
							v-model="query.end_date" @change="changeDate2" />
					</view>
				</view>

				<button style="width: 120rpx;  font-size: 28rpx;" type="primary" @click="get_data">查询</button>
			</view>
		</view>

		<!-- 缴费项目快速查询 -->
		<view class="quick-query gui-padding">
			<view class="gui-h4 gui-color-black gui-margin-bottom">快速查询历史账单</view>
			<view class="gui-flex gui-wrap" style="gap: 20rpx;">
				<view v-for="(item, index) in quickQueryItems" :key="index" 
					class="quick-item gui-border gui-border-radius-large gui-padding-small"
					:class="selectedQuickItem === index ? 'gui-bg-blue gui-color-white' : 'gui-bg-white'"
					@click="selectQuickItem(index)">
					<text>{{item.name}}</text>
				</view>
			</view>
		</view>

		<view>
			<view v-for="(item,index) in list" :key="index"
				class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-bg-white gui-padding">
				<view style="width: 120rpx;display: flex;align-items: center;justify-content: center;">
					<image :src="get_pay_icon(item.pay_type)" style="width: 60rpx;height: 60rpx;" mode="widthFix">
					</image>
				</view>
				<view class="gui-padding" style="flex: 1;line-height: 40rpx;">
					<view class="gui-color-black gui-h5">
						{{item.name}}({{item.fee_name}})
					</view>
					<view class="gui-color-gray gui-h6">
						缴费时间: {{item.pay_time}}
					</view>
					<!-- 工会费特殊显示：缴费时间类型 -->
					<view v-if="item.fee_name && item.fee_name.includes('工会费') && Number(item.pay_status) === 1" 
						class="gui-color-blue gui-h6">
						支付方式: {{item.pay_type_text}}
					</view>
				</view>

				<view class="gui-padding" style="width: 160rpx;text-align: right;">
					<view class="gui-color-red gui-h5 gui-bold">
						￥{{item.amount}}
					</view>
					<!-- 缴费状态显示 -->
					<view v-if="item.pay_status !== undefined" 
						:class="getStatusClass(item.pay_status)"
						class="gui-h6 gui-padding-small gui-border-radius-small status-text">
						{{item.pay_status_text || getStatusText(item.pay_status)}}
					</view>
				</view>
			</view>
			
			<!-- 工会费按时间倒序显示 -->
			<view v-if="query.type === 1 && ghfHistory.length > 0" class="gui-margin-top">
				<view class="gui-h4 gui-color-black gui-padding">工会费缴费历史（按时间倒序）</view>
				<view v-for="(item, index) in ghfHistory" :key="'ghf-'+index"
					class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-bg-white gui-padding">
					<view style="width: 120rpx;display: flex;align-items: center;justify-content: center;">
						<image :src="get_pay_icon(item.pay_type)" style="width: 60rpx;height: 60rpx;" mode="widthFix">
						</image>
					</view>
					<view class="gui-padding" style="flex: 1;line-height: 40rpx;">
						<view class="gui-color-black gui-h5">
							{{item.name}}(工会费)
						</view>
						<view class="gui-color-gray gui-h6">
							缴费时间: {{item.pay_time}}
						</view>
						<view class="gui-color-blue gui-h6">
							支付方式: {{item.pay_type_text}}
						</view>
					</view>
					<view class="gui-padding" style="width: 160rpx;text-align: right;">
						<view class="gui-color-red gui-h5 gui-bold">
							￥{{item.amount}}
						</view>
						<view class="gui-color-green gui-h6 gui-padding-small gui-border-radius-small status-text">
							缴费成功
						</view>
					</view>
				</view>
			</view>
			
			<view style="text-align: center; margin-top: 100rpx;" v-if="list.length <= 0">
				暂无数据
			</view>
		</view>

		<!-- 分页组件 -->
		<view v-if="total > 0" class="gui-margin-top">
			<uni-pagination 
				style="width: 92%; margin: 0 auto;" 
				:show-icon="true" 
				:total="total"
				:pageSize="pageSize" 
				@change="changePage" />
		</view>

	</view>
</template>

<script>
	import graceJS from '@/Grace6/js/grace.js';
	import menuBar from "./menu_bar"
	export default {
		components: {
			menuBar
		},
		data() {
			return {
				show_calendar: false,
				list: [],
				ghfHistory: [], // 工会费历史记录
				query: {
					typelist: ['缴费类别', '工会费', '互助金', '团费', '其它'],
					type: 0,
					start_date: '',
					end_date: ''
				},
				quickQueryItems: [
					{ name: '本月', type: 'current_month' },
					{ name: '上月', type: 'last_month' },
					{ name: '本季度', type: 'current_quarter' },
					{ name: '本年', type: 'current_year' },
					{ name: '最近3个月', type: 'last_3_months' },
					{ name: '最近6个月', type: 'last_6_months' }
				],
				selectedQuickItem: -1,
				page: 1,
				pageSize: 20,
				total: 0
			}
		},
		onShow() {
			// console.log(graceJS.now('str'));
			let dt = graceJS.now('str');
			this.query.start_date = dt.split('-')[0] + '-05-01';
			this.query.end_date = dt.split(' ')[0];
			this.get_data()
		},
		methods: {
			changeDate1(e) {
				console.log(e);
				this.query.start_date = e
				this.$refs.ref_datePicker1.close();
			},
			changeDate2(e) {
				console.log(e);
				this.query.end_date = e
				this.$refs.ref_datePicker2.close();
			},
			openCalendar1() {
				//this.$refs.calendar.open();
				this.show_calendar = true;
			},
			select_type(e) {
				console.log(e)
				this.query.type = e;
				// this.get_data();
			},
			// 快速查询选择
			selectQuickItem(index) {
				this.selectedQuickItem = index;
				const item = this.quickQueryItems[index];
				this.setQuickDateRange(item.type);
				this.get_data();
			},
			// 设置快速查询日期范围
			setQuickDateRange(type) {
				const now = new Date();
				const year = now.getFullYear();
				const month = now.getMonth();
				const day = now.getDate();
				
				switch(type) {
					case 'current_month':
						this.query.start_date = `${year}-${String(month + 1).padStart(2, '0')}-01`;
						this.query.end_date = `${year}-${String(month + 1).padStart(2, '0')}-${day}`;
						break;
					case 'last_month':
						const lastMonth = month === 0 ? 11 : month - 1;
						const lastMonthYear = month === 0 ? year - 1 : year;
						this.query.start_date = `${lastMonthYear}-${String(lastMonth + 1).padStart(2, '0')}-01`;
						this.query.end_date = `${lastMonthYear}-${String(lastMonth + 1).padStart(2, '0')}-${new Date(lastMonthYear, lastMonth + 1, 0).getDate()}`;
						break;
					case 'current_quarter':
						const quarter = Math.floor(month / 3);
						const quarterStartMonth = quarter * 3;
						this.query.start_date = `${year}-${String(quarterStartMonth + 1).padStart(2, '0')}-01`;
						this.query.end_date = `${year}-${String(month + 1).padStart(2, '0')}-${day}`;
						break;
					case 'current_year':
						this.query.start_date = `${year}-01-01`;
						this.query.end_date = `${year}-${String(month + 1).padStart(2, '0')}-${day}`;
						break;
					case 'last_3_months':
						const threeMonthsAgo = new Date(year, month - 3, day);
						this.query.start_date = `${threeMonthsAgo.getFullYear()}-${String(threeMonthsAgo.getMonth() + 1).padStart(2, '0')}-${threeMonthsAgo.getDate()}`;
						this.query.end_date = `${year}-${String(month + 1).padStart(2, '0')}-${day}`;
						break;
					case 'last_6_months':
						const sixMonthsAgo = new Date(year, month - 6, day);
						this.query.start_date = `${sixMonthsAgo.getFullYear()}-${String(sixMonthsAgo.getMonth() + 1).padStart(2, '0')}-${sixMonthsAgo.getDate()}`;
						this.query.end_date = `${year}-${String(month + 1).padStart(2, '0')}-${day}`;
						break;
				}
			},
			get_pay_icon(t) {
				switch (t) {
					case 'wx':
						return '../../static/homePage/wx.png'
					case 'abcBridge':
						return '../../static/homePage/xcx.png'
					case 'OPEN':
						return '../../static/homePage/xcx.png'
					case 'app':
						return '../../static/homePage/nh.png'
					default:
						return '../../static/homePage/wx.png'
				}
			},
			// 获取状态样式类
			getStatusClass(status) {
				switch(Number(status)) {
					case 1:
						return 'gui-color-green gui-bg-green-light';
					case 0:
						return 'gui-color-orange gui-bg-orange-light';
					case -1:
						return 'gui-color-red gui-bg-red-light';
					default:
						return 'gui-color-gray gui-bg-gray-light';
				}
			},
			// 获取状态文本
			getStatusText(status) {
				switch(Number(status)) {
					case 1:
						return '缴费成功';
					case 0:
						return '处理中';
					case -1:
						return '缴费失败';
					default:
						return '未知状态';
				}
			},
			// 获取支付状态文本（适配数字状态）
			getPayStatusText(status) {
				switch(Number(status)) {
					case 1:
						return '缴费成功';
					case 0:
						return '处理中';
					case -1:
						return '缴费失败';
					default:
						return '未知状态';
				}
			},
			// 分页处理
			changePage(e) {
				if (e.type == 'next') {
					this.page++;
				} else if (e.type == 'prev') {
					this.page--;
				}
				this.get_data();
			},
			get_data() {
				let parm = {
					"page": this.page,
					"limit": this.pageSize,
				}
				if (this.query.type == 0) parm.type = null;
				if (this.query.type == 1) parm.type = "feenoticeform";
				if (this.query.type == 2) parm.type = "hzj";
				if (this.query.type == 3) parm.type = "tw";
				if (this.query.type == 4) parm.type = "other";
				
				// 根据实际接口，添加状态过滤
				parm.status = 1; // 只查询缴费成功的记录

				if (this.query.start_date != '') {
					parm.start_date = this.query.start_date
				}
				if (this.query.end_date != '') {
					parm.end_date = this.query.end_date
				}
				console.log('parm: ', parm);
				let self = this;
				this.$boya.NGet("/app/pay/order_list", parm, function(res) {
					console.log('res: ', res);
					self.list = Array.isArray(res.data) ? res.data : [];
					self.total = self.list.length;
					
					// 如果是工会费查询，额外获取工会费历史记录
					if (self.query.type == 1) {
						self.getGhfHistory();
					} else {
						self.ghfHistory = [];
					}
					
					// 处理支付状态显示
					self.list.forEach(item => {
						item.pay_status_text = self.getPayStatusText(item.pay_status);
						item.pay_type_text = self.getPayTypeText(item.pay_type);
					});
				})
			},
			// 获取工会费历史记录（按时间倒序，只显示缴费成功的）
			getGhfHistory() {
				let self = this;
				let parm = {
					"page": 1,
					"limit": 50, // 获取更多记录用于排序
					"type": "feenoticeform",
					"status": 1 // 只查询缴费成功的
				};
				
				if (this.query.start_date != '') {
					parm.start_date = this.query.start_date
				}
				if (this.query.end_date != '') {
					parm.end_date = this.query.end_date
				}
				
				this.$boya.NGet("/app/pay/order_list", parm, function(res) {
					console.log('工会费历史记录: ', res);
					if (res.data && Array.isArray(res.data)) {
						// 按时间倒序排序，只显示缴费成功的记录
						self.ghfHistory = res.data
							.filter(item => Number(item.pay_status) === 1)
							.sort((a, b) => new Date(b.pay_time) - new Date(a.pay_time));
						
						// 处理支付状态显示
						self.ghfHistory.forEach(item => {
							item.pay_status_text = self.getPayStatusText(item.pay_status);
							item.pay_type_text = self.getPayTypeText(item.pay_type);
						});
					}
				}, function(err) {
					console.log('获取工会费历史记录失败: ', err);
					self.ghfHistory = [];
				})
			}
		}

	}
</script>

<style>
	.graceSelectMenuItem {
		width: 160rpx;
		flex: 1;
	}

	.uni-calendar__content-mobile {
		padding-bottom: 300rpx !important;
	}

	.uni-date-btn--ok {
		padding-bottom: 300rpx !important;
	}
	
	.quick-query {
		background-color: #f8f9fa;
		border-bottom: 1px solid #e9ecef;
	}
	
	.quick-item {
		min-width: 120rpx;
		text-align: center;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.quick-item:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.1);
	}
	
	.status-text {
		white-space: nowrap;
		font-size: 24rpx;
	}
</style>
<style scoped>
	.uni-date-btn--ok {
		padding-bottom: 300rpx !important;
	}
</style>